﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace TextDataExtractor.DEML {
	public class SelectivePattern : CompositePattern {
		private AbstractPattern highestMatchPattern = null;

		public override int match(string input) {
			highestMatchPattern = null;
			int highestMatchValue = 0;

			foreach (AbstractPattern pattern in SubPatterns) {
				int matchValue = pattern.match(input);
				
				Debug.WriteLine("match {0}: {1}", pattern.FullName, matchValue);
				
				if (matchValue > highestMatchValue) {
					highestMatchValue = matchValue;
					highestMatchPattern = pattern;
				}
			}

			if (highestMatchPattern != null) {
				StartIndex = highestMatchPattern.StartIndex;
				EndIndex = highestMatchPattern.EndIndex;
			}

			IsSuccess = highestMatchValue > 0;
			return highestMatchValue;
		}

		protected override void doExtraction(ExecutionContext context) {
			if (highestMatchPattern != null)
				highestMatchPattern.performExtraction(context);
		}

		public override IEnumerable<AbstractPattern> getMatchedPatterns(Predicate<AbstractPattern> pred) {
			if (IsSuccess) {
				foreach (AbstractPattern p in highestMatchPattern.getMatchedPatterns(pred))
					yield return p;
			}
		}

		public override string getMatchedPatternName(int indent) {
			if (IsSuccess && highestMatchPattern != null)
				return highestMatchPattern.getMatchedPatternName(indent);
			return String.Empty;
		}
	}

}
